<template>
    <!-- 课程分类管理 -->
    <div class="scheme">
        <div class="header-box">
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
                <el-form-item label="名称搜索：">
                    <el-input v-model="formInline.name" placeholder="请输入搜索分类名称"></el-input>
                </el-form-item>
                <el-form-item label="创建时间:">
                    <el-date-picker v-model="formInline.created_at" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"
                                    type="datetimerange" range-separator="至" start-placeholder="开始日期"
                                    end-placeholder="结束日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="更新时间:">
                    <el-date-picker v-model="formInline.updated_at" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"
                                    type="datetimerange" range-separator="至" start-placeholder="开始日期"
                                    end-placeholder="结束日期">
                    </el-date-picker>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="searchForm">搜索</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="success" icon="el-icon-plus" @click="add">新增分类</el-button>
                </el-form-item>
            </el-form>

        </div>
        <div class="tables">
            <el-table border :data="tableData" max-height="650" highlight-current-row :row-style="{height: '20px'}"
                      :header-cell-style="{background:'#e6e6e6',color:'#000000'}">
                <el-table-column prop="id" align="center" label="ID" width="60">
                </el-table-column>
                <el-table-column prop="name" align="center" label="分类名称">
                </el-table-column>
                <el-table-column prop="image" label="图片" align="center">
                    <template slot-scope="scope">
                        <img style="width: 50px;height: 50px;display: block;margin: 0 auto;" :src="scope.row.image" alt="" srcset="" />
                    </template>
                </el-table-column>
                <el-table-column prop="order" align="center" label="排序">
                </el-table-column>
                <el-table-column prop="created_at" align="center" label="创建时间">
                </el-table-column>
                <el-table-column prop="updated_at" align="center" label="更新时间">
                </el-table-column>
                <el-table-column prop="status" align="center" label="状态">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'"
                                disable-transitions>{{ scope.row.status === 1 ? '开启' : '关闭' }}
                        </el-tag>
                    </template>
                </el-table-column>

                <el-table-column align="center" label="操作" width="250">
                    <template slot-scope="scope">
                        <el-button size="mini" type="success" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑
                        </el-button>
                        <el-button size="mini" type="danger" plain icon="el-icon-delete"
                                   @click="handleDelete(scope.row)">删除
                        </el-button>
                    </template>

                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                               :current-page.sync="page" :page-sizes="[15, 20, 50, 100]" :page-size="limit"
                               layout="total, sizes, prev, pager, next, jumper" :total="total">
                </el-pagination>
            </div>
        </div>

        <!-- 新增/编辑弹框 -->
        <el-dialog :title="title" :visible.sync="dialogAdd" width="40%">
            <el-form :model="form" label-width="80px">
                <el-form-item label="名称:" style="width: 60%">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="图片" prop="image">
                    <el-upload
                        class="avatar-uploader"
                        :action="uploadUrl"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="form.image" :src="form.image" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        <div class="el-upload__tip" slot="tip">只能上传jpg/png/gif文件，且不超过10M，建议80*80</div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="状态:">
                    <el-switch class="switch" v-model="form.status" active-value="1" inactive-value="2">
                    </el-switch>
                </el-form-item>
                <el-form-item label="排序:" style="width: 60%">
                    <el-input type="number" v-model="form.order"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogAdd = false">取 消</el-button>
                <el-button type="primary" @click="addCourseType">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import { isEmpty } from "../../../api/http";

export default {
  name: "course_type",
  data() {
    return {
      formInline: {
        name: "",
        created_at: [],
        updated_at: [],
      },
      form: {
        name: "",
        image: "",
        status: "2",
        order: "",
      },
      tableData: [],
      dialogAdd: false, //默认新增课程弹框隐藏
      title: "新增分类", //默认新增
      isEdit: false, //默认为新增
      id: "",
      page: 1, //默认第一页
      limit: 15, //默认一页显示10条数据
      total: 0,
      uploadUrl: "",
    };
  },
  created() {
    this.getCourseTypeList();
    this.uploadUrl = this.$api.imageUpload;
  },
  activated() {
    this.getCourseTypeList();
  },
  methods: {
    searchForm() {
      this.getCourseTypeList();
    },
    handleAvatarSuccess(res, file) {
      this.form.image = URL.createObjectURL(file.raw);
      if (res.code == 200) {
        this.form.image = res.data.url;
      }
    },
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/gif";
      console.log("file.type", file.type);
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 jpeg、png或者gif格式!");
      }
      if (!isLt10M) {
        this.$message.error("上传头像图片大小不能超过 10MB!");
      }
      return isJPG && isLt10M;
    },
    initForm() {
      this.form.name = "";
      this.form.image = "";
      this.form.status = "";
      this.form.order = "";
    },
    // 点击新增课程按钮
    add() {
      this.title = "新增分类";
      this.initForm();
      this.dialogAdd = true;
      this.isEdit = false;
    },

    // 获取列表
    getCourseTypeList(page, limit) {
      let params = {
        page: page,
        per_page: limit,
        name: this.formInline.name,
      };
      if (!isEmpty(this.formInline.created_at)) {
        params.start_created_at = this.formInline.created_at[0];
        params.end_created_at = this.formInline.created_at[1];
      }
      if (!isEmpty(this.formInline.updated_at)) {
        params.start_updated_at = this.formInline.updated_at[0];
        params.end_updated_at = this.formInline.updated_at[1];
      }
      this.$get(this.$api.courseTypeApi, params).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data.data;
          this.total = res.data.total;
        } else {
          return this.$message.error(res.msg);
        }
      });
    },

    // 点击编辑按钮
    handleEdit(row) {
      this.title = "编辑分类";
      this.id = row.id;
      this.form.name = row.name;
      this.form.image = row.image;
      this.form.status = row.status.toString();
      this.form.order = row.order;
      this.dialogAdd = true;
      this.isEdit = true;
    },
    // 点击删除按钮
    handleDelete(row) {
      this.$confirm("此操作将永久删除该分类, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$delete(this.$api.courseTypeApi + "/" + row.id).then((res) => {
            if (res.code == 200) {
              this.getCourseTypeList(this.page, this.limit);
              return this.$message.success("删除成功！");
            } else {
              return this.$message.error(res.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 分页
    handleSizeChange(size) {
      this.limit = size;
      this.getCourseTypeList(this.page, this.limit);
    },
    handleCurrentChange(index) {
      this.page = index;
      this.getCourseTypeList(this.page, this.limit);
    },
    // 点击查询按钮
    submitForm() {
      this.getCourseTypeList(this.page, this.limit);
    },

    // 点击新增课程确定按钮
    addCourseType() {
      if (this.form.name == "") {
        return this.$message.error("请输入名称！");
      }
      if (this.form.image == "") {
        return this.$message.error("请上传封面图！");
      }
      if (this.form.status == "") {
        return this.$message.error("请选择状态！");
      }
      if (this.form.order == "") {
        return this.$message.error("请填入排序！");
      }
      let params = {
        name: this.form.name,
        image: this.form.image,
        status: this.form.status,
        order: this.form.order,
      };
      if (this.isEdit) {
        this.$put(this.$api.courseTypeApi + "/" + this.id, params).then(
          (res) => {
            if (res.code == 200) {
              this.form.name = "";
              this.form.status = 2;
              this.dialogAdd = false;
              this.getCourseTypeList(this.page, this.limit);
              return this.$message.success("编辑成功！");
            } else {
              return this.$message.error(res.msg);
            }
          }
        );
      } else {
        this.$post(this.$api.courseTypeApi, params).then((res) => {
          if (res.code == 200) {
            this.dialogAdd = false;
            this.getCourseTypeList(this.page, this.limit);
            return this.$message.success("新增成功！");
          } else {
            return this.$message.error(res.msg);
          }
        });
      }
    },
  },
};
</script>

<style scoped>
.pagination {
  text-align: center;
}
.avatar{
    width: 100%;
    height: 100%;
    display: block;
}

</style>
